package com.slh.touchandroid.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.slh.touchandroid.R;
import com.slh.touchandroid.utils.Utils;

public class BrightnessFragment extends BaseFragment implements
		OnSeekBarChangeListener {
	// =================================================================
	private static final int MIN_BRIGHTNESS = 10;
	private ImageView mImgBrightness;
	private SeekBar mSbBrightness;

	// =================================================================
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRetainInstance(true);
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_brightness,
				container, false);
		mImgBrightness = (ImageView) rootView
				.findViewWithTag(getString(R.string.tag_brightness));
		int brightness = Utils.getBrightness(getActivity());
		mImgBrightness.getDrawable().setAlpha(255 - brightness);
		mSbBrightness = (SeekBar) rootView
				.findViewWithTag(getString(R.string.tag_brightness_bar));
		mSbBrightness.setMax(255);
		mSbBrightness.setProgress(brightness);
		mSbBrightness.setOnSeekBarChangeListener(this);
		return rootView;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		mImgBrightness.getDrawable().setAlpha(255 - checkBrightness(progress));
		updateBrightness(checkBrightness(progress));

	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		int progress = checkBrightness(seekBar.getProgress());
		mImgBrightness.getDrawable().setAlpha(255 - progress);
		updateBrightness(progress);
	}

	private void updateBrightness(int brightness) {
		Utils.setBrightness(getActivity(), brightness);
	}

	private int checkBrightness(int brightness) {
		if (brightness < MIN_BRIGHTNESS) {
			brightness = MIN_BRIGHTNESS;
		}
		return brightness;
	}

	// ==========================================================================
}
